# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\phone_validation\tw.py
__author__ = "Attila Gerendi (Sanyi)"
import random, string, logging, datetime
from sqlalchemy import select as sql_select
from twilio.rest import Client
from settings_provider import settings
from db.tables.phone_validation import PhoneValidationRow, PhoneValidationTable
from db.tables.users import UserConfirmation
from db.data.users import prepare_user_data
from db import Connection

_logger = logging.getLogger("helpers.phone_validation_twilio")


def code_call(shard, user_id):
    with Connection(shard) as (db):
        user = prepare_user_data(db, user_id=user_id)
        if (
            not user
            or not user["enabled"]
            or user["confirmation"] != UserConfirmation.NEEDS_VALIDATION
        ):
            _logger.warning("invalid user status %s:%s", shard, user_id)
            return
    phone_number = user["phone"]
    code = ("").join((random.choice(string.digits) for _ in range(0, 4)))
    client = Client(
        settings["phone_validation.twilio.account_sid"],
        settings["phone_validation.twilio.account_secret"],
    )
    try:
        call = client.calls.create(
            to=phone_number,
            from_=settings["phone_validation.twilio.from_number"],
            url=settings["phone_validation.twilio.twiml_bin.one_time_token"]
            + "?c1=%s&c2=%s&c3=%s&c4=%s" % (code[0], code[1], code[2], code[3]),
        )
    except Exception as e:
        _logger.error(
            "calling %s:%s [%s] failed with %s", shard, user["email"], user_id, e
        )
    else:
        _logger.info(
            "called %s:%s [%s], call_id: %s", shard, user["email"], user_id, call.sid
        )
        with Connection(shard) as (db):
            q = sql_select((PhoneValidationRow.data,)).where(
                PhoneValidationRow.user_id == user_id
            )
            data = db.execute(q).scalar()
            if not data:
                data = dict(
                    request_count=1,
                    code=code,
                    last=datetime.datetime.now().isoformat(),
                    phone=phone_number,
                )
                q = PhoneValidationTable.insert().values(user_id=user_id, data=data)
                db.execute(q)
            else:
                data = dict(data)
                data["request_count"] = data.get("request_count", 0) + 1
                data["code"] = code
                data["last"] = datetime.datetime.now().isoformat()
                data["phone"] = phone_number
                q = (PhoneValidationTable.update(values=dict(data=data))).where(
                    PhoneValidationRow.user_id == user_id
                )
                db.execute(q)
